

import os
import re
import galscript

def parse_filename(filepath):
    filename = os.path.basename(filepath)

    # 使用正则表达式匹配模式
    pattern = r'^(\d+)-(.*?)_processed\.xml$'
    match = re.match(pattern, filename)

    if not match:
        raise ValueError(f"文件名格式不正确: {filename}")

    # 提取各部分信息
    file_id = match.group(1)
    name = match.group(2)

    return {
        'filename': filename,
        'id': file_id,
        'name': name
    }

def process_file(file, results):
  if ("Scenes.xml" in file): return

  data = parse_filename(file)
  results.append(f'<Scene ID=\'{data["id"]}\' Name=\'{data["name"]}\' Icon=\'image/.png\'>{data["filename"]}</Scene>')

  pre_processor = galscript.PreProcessor(file)

  bg_used = []
  for line in pre_processor.content:
     if "Type=\"Bg\"" in line:
        bg_used.append(pre_processor.pick_str(line, '>([^"]*)<'))


  results.append(",".join(bg_used))
  print(file)

  pass

if __name__ == "__main__":
    args = galscript.FileManager()  # 使用imodule中的Args类
    results = []
    args.foreach_file([".xml"], lambda file: process_file(file, results))

    with open(args.get_output_file("Scenes.xml"), "w", encoding="utf-8") as f:
      for line in results:
          f.write(f"{line}\n")  # 每次写入一行
